package com.zjuh.goodboy.index.lucene;

import java.io.File;
import java.io.IOException;
import java.util.Collection;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.index.CorruptIndexException;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;
import org.apache.lucene.util.Version;

import com.zjuh.goodboy.index.DocumentHandler;
import com.zjuh.goodboy.items.Item;

public class LuceneDocumentHandler implements DocumentHandler {

	private File indexDir;
	
	private IndexWriter indexWriter;
	
	private Analyzer analyzer;
	
	private LuceneDocumentSearcherHolder luceneDocumentSearcherHolder;
	
	private boolean documentModified = false;
	
	public LuceneDocumentHandler(File indexDir, Analyzer analyzer, LuceneDocumentSearcherHolder luceneDocumentSearcherHolder) {
		super();
		this.indexDir = indexDir;
		this.analyzer = analyzer;
		this.luceneDocumentSearcherHolder = luceneDocumentSearcherHolder;
		openWriter();
	}

	
	@Override
	public void updateItems(Collection<Item> items) {
		for (Item item : items) {
			updateItem(item);
		}
	}


	@Override
	public void updateItem(Item item) {
		Document doc = LuceneDocUtil.toDocument(item);
		try {
			long itemId = item.getId();
			if (itemId != 0L) {
				indexWriter.updateDocument(new Term("id", String.valueOf(itemId)), doc);
			} else {
				indexWriter.addDocument(doc);
			}
			documentModified = true;
		} catch (CorruptIndexException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	

	private void openWriter() {
		try {
			Directory directory = FSDirectory.open(indexDir);
			IndexWriterConfig indexWriterConfig = new IndexWriterConfig(Version.LUCENE_35, analyzer);
			indexWriterConfig.setOpenMode(OpenMode.CREATE_OR_APPEND);
			indexWriter = new IndexWriter(directory, indexWriterConfig);
		} catch (CorruptIndexException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void commit() {
		try {
			indexWriter.commit();
		} catch (CorruptIndexException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public void close() {
		try {
			indexWriter.close();
			if (documentModified) {
				LuceneDocumentSearcher searcher = luceneDocumentSearcherHolder.getLuceneDocumentSearcher();
				if (searcher != null) {
					searcher.reopen();
				}
			}
		} catch (CorruptIndexException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}



}
